package com.icinfo.cloud.provider.punish.actscode.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.exception.BusinessException;
import com.icinfo.cloud.provider.punish.actscode.dto.ActsCodeRequest;
import com.icinfo.cloud.provider.punish.actscode.dto.CasePunishInfoListQueryDto;
import com.icinfo.cloud.provider.punish.actscode.enums.CaseNotGivePunishReasonEnum;
import com.icinfo.cloud.provider.punish.actscode.enums.CaseProgressEnum;
import com.icinfo.cloud.provider.punish.actscode.mapper.CaseActsCodeInfoMapper;
import com.icinfo.cloud.provider.punish.actscode.model.CaseActsCodeInfo;
import com.icinfo.cloud.provider.punish.actscode.service.ICaseActsCodeService;
import com.icinfo.cloud.provider.punish.actscode.vo.*;
import com.icinfo.cloud.provider.punish.common.datareport.enums.ReportDataTypeEnum;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataReportRecord;
import com.icinfo.cloud.provider.punish.common.datareport.model.CaseDataReportStageInfo;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.evaluate.model.EvaluateRecord;
import com.icinfo.cloud.provider.punish.mapper.*;
import com.icinfo.cloud.provider.punish.service.ICasePartiesRecordService;
import com.icinfo.cloud.provider.punish.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.*;
import com.icinfo.cloud.provider.punish.vo.EvaluateInfoVo;
import com.icinfo.cloud.workflow.work.mapper.WorkFlowRollSubMainInfoMapper;
import com.icinfo.cloud.workflow.work.model.WorkFlowRollSubMainInfo;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringSubstitutor;
import org.apache.commons.text.lookup.StringLookupFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Desc 行为码查询案件详情service
 * @Author mahan
 * @Date 2022/11/9
 */
@Service
public class CaseActsCodeServiceImpl extends MyBatisServiceSupport implements ICaseActsCodeService {

    @Resource
    private CaseMainInfoMapper caseMainInfoMapper;
    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;
    @Resource
    private CaseReasonMainRecordMapper caseReasonMainRecordMapper;
    @Resource
    private CasePartiesRecordMapper casePartiesRecordMapper;
    @Resource
    private CasePartiesLegalInfoMapper casePartiesLegalInfoMapper;
    @Resource
    private CasePartiesPersonInfoMapper casePartiesPersonInfoMapper;
    @Resource
    private CaseMainDetailAuxiliaryInfoMapper caseMainDetailAuxiliaryInfoMapper;
    @Resource
    private CaseMainDetailSimpleInfoMapper caseMainDetailSimpleInfoMapper;
    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private CaseMainDetailInfoMapper caseMainDetailInfoMapper;
    @Resource
    private CaseActsCodeInfoMapper caseActsCodeInfoMapper;
    @Resource
    private CaseDataReportRecordMapper caseDataReportRecordMapper;
    @Resource
    private CaseDataReportStageInfoMapper caseDataReportStageInfoMapper;
    @Resource
    private CasePaymentMainRecordMapper casePaymentMainRecordMapper;
    @Resource
    private EvaluateRecordMapper evaluateRecordMapper;
    @Resource
    private ISysDepartParamService sysDepartParamService;
    @Resource
    private WorkFlowRollSubMainInfoMapper workFlowRollSubMainInfoMapper;

    @Value("${payment.url}")
    private String payUrl;


    /**
     * 根据行为码，查询案件信息
     *
     * @param caseActsCode
     * @return
     */
    @Override
    public CaseActsCodeDetailVo getCaseDetailByActsCode(String caseActsCode) {
        CaseActsCodeDetailVo reVo = new CaseActsCodeDetailVo();
        //获取主表数据
        CaseMainInfo queryParam = new CaseMainInfo();
        queryParam.setCaseActsCode(caseActsCode);
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectOne(queryParam);
        if (caseMainInfo == null) {
            throw new BusinessException("未查询到案件信息");
        }
        this.setMainInfo(caseMainInfo, reVo);
        //获取办案人员信息
        Example handlePersonRecordExample = new Example(CaseHandlePersonRecord.class);
        handlePersonRecordExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
        List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(handlePersonRecordExample);
        handlePersonRecords.forEach(e -> {
            if (HandlePersonTypeEnum.MAIN.getCode().equals(e.getHandlePersonType())) {
                reVo.setMainHandlePerson(e.getHandlePersonName());
            } else if (HandlePersonTypeEnum.ASSIST.getCode().equals(e.getHandlePersonType())) {
                reVo.setHelpHandlePerson(e.getHandlePersonName());
            }
        });
        //获取案由
        reVo.setCaseReasons(this.getCaseReasons(caseMainInfo.getId()));
        //获取当事人信息
        //多当事人合并处罚时使用
        List<String> partyNameList = new ArrayList<>();
        //多当事人时，当事人map集合
        Map<String, String> partyTypeMap = new HashMap<>();
        this.getPartyInfo(caseMainInfo, partyNameList, partyTypeMap, reVo);

        //获取处罚决定信息
        this.getPunishInfoList(caseMainInfo, partyTypeMap, partyNameList, reVo);
        reVo.setCaseCreateTime(caseMainInfo.getCaseCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        return reVo;
    }

    /**
     * 检查详情页面，获取行政处罚列表
     *
     * @return
     */
    @Override
    public List<CasePunishInfoListVo> getPunishInfoList(CasePunishInfoListQueryDto dto) {
        if (dto.getCaseActsCodeList() == null || dto.getCaseActsCodeList().isEmpty()) {
            throw new BusinessException("案件码信息不能为空");
        }
        List<CasePunishInfoListVo> reList = caseMainInfoMapper.getPunishInfoList(dto.getCaseActsCodeList());
        if (reList == null || reList.isEmpty()) {
            throw new BusinessException("无关联行政处罚信息");
        }
        reList.forEach(e -> {
            //获取案由
            e.setCaseReason(this.getCaseReasons(e.getCaseId()));
        });
        return reList;
    }

    /**
     * 公众扫码，获取案件公示信息
     *
     * @param caseActsCode
     * @return
     */
    @Override
    public CasePublicInfoVo getCasePublicInfo(String caseActsCode) {
        CasePublicInfoVo reVo = new CasePublicInfoVo();
        //获取案件条形码
        CaseActsCodeInfo actsCodeInfoParam = new CaseActsCodeInfo();
        actsCodeInfoParam.setCaseActsCode(caseActsCode);
        CaseActsCodeInfo caseActsCodeInfo = caseActsCodeInfoMapper.selectOne(actsCodeInfoParam);
        if (caseActsCodeInfo != null) {
            reVo.setBarCodeUrl(caseActsCodeInfo.getBarCodeUrl());
        }
        //获取主表数据
        CaseMainInfo queryParam = new CaseMainInfo();
        queryParam.setCaseActsCode(caseActsCode);
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectOne(queryParam);
        if (caseMainInfo == null) {
            throw new BusinessException("未查询到案件信息");
        }
        //获取案由
        String caseReason = this.getCaseReasons(caseMainInfo.getId());
        reVo.setCaseReason(caseReason);
        reVo.setCaseOrgName(caseMainInfo.getCaseOrgName());
        reVo.setCaseRegisterTime(caseMainInfo.getCaseRegistTime());

        List<CasePublicInfoListVo> punishDecisionDocuments = caseMainInfoMapper.getCasePunishDocuments(caseMainInfo.getId());
        List<CasePublicInfoListVo> reList = new ArrayList<>();
        //如果没有查出数据，则返回
        if (punishDecisionDocuments == null || punishDecisionDocuments.isEmpty()) {
            reVo.setNoDecisionReason("案件处罚决定暂未做出");
            return reVo;
        } else {
            for (CasePublicInfoListVo vo : punishDecisionDocuments) {
                //查询是否公示
                if (!checkDataReport(caseMainInfo.getId(), caseMainInfo.getHandleType(), vo.getPartyId())) {
                    continue;
                }
                //简易程序不公示
                if(Constant.STRING_1.equals(caseMainInfo.getCaseType())){
                    continue;
                }
                vo.setCaseReason(caseReason);
                vo.setCaseOrgName(reVo.getCaseOrgName());
                vo.setCaseRegisterTime(reVo.getCaseRegisterTime());
                if(CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())){
                    vo.setPunishDecisionDate(caseMainInfo.getCaseVerdictEndTime());
                }else if(CaseTypeEnum.NORMAL_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())){
                    //获取公示内容
                    vo.setDecisionContent(this.getPublicityContent(caseMainInfo.getId(), vo.getPartyId(), caseMainInfo.getHandleType()));
                    //如果是合并处罚，查询出party名称
                    if (HandleTypeEnum.MERGE_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
                        vo.setPartyName(this.getCasePublicPartyName(caseMainInfo.getId()));
                    }
                }
                reList.add(vo);
                reVo.setCasePublicInfoListVos(reList);
            }
            if (reList.isEmpty()) {
                reVo.setNoDecisionReason("案件处罚决定暂未公示");
            } else {
                reVo.setCasePublicInfoListVos(reList);
            }
        }
        return reVo;
    }




    /**
     * 获取处罚公示内容
     * @param caseId
     * @param partyId
     * @param handleType
     * @return
     */
    private String getPublicityContent(String caseId, String partyId, String handleType) {
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
            CaseMainDetailAuxiliaryInfo param = new CaseMainDetailAuxiliaryInfo();
            param.setCaseId(caseId);
            param.setPartyId(partyId);
            CaseMainDetailAuxiliaryInfo caseMainDetailAuxiliaryInfo = caseMainDetailAuxiliaryInfoMapper.selectOne(param);
            return caseMainDetailAuxiliaryInfo.getPublicityContent();
        } else {
            CaseMainDetailInfo param = new CaseMainDetailInfo();
            param.setCaseId(caseId);
            CaseMainDetailInfo caseMainDetailInfo = caseMainDetailInfoMapper.selectOne(param);
            return caseMainDetailInfo.getPublicityContent();
        }
    }

    /**
     * 获取公示案件，合并处罚当事人名称
     *
     * @param caseId
     * @return
     */
    private String getCasePublicPartyName(String caseId) {
        Example partyExample = new Example(CasePartiesRecord.class);
        partyExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", "1");
        partyExample.orderBy("partyType").desc();
        List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
        if (partiesRecords == null || partiesRecords.isEmpty()) {
            return null;
        }
        List<String> nameList = new ArrayList<>();
        partiesRecords.forEach(e -> {
            nameList.add(e.getPartyName());
        });
        return CollUtil.join(nameList, "、");
    }

    /**
     * 校验是否公示
     *
     * @param caseId
     * @param partyId
     * @return
     */
    private boolean checkDataReport(String caseId, String handleType, String partyId) {
        if (!HandleTypeEnum.PART_PUNISH.getCode().equals(handleType)) {
            partyId = "";
        }
        Example report = new Example(CaseDataReportRecord.class);
        Example.Criteria criteria = report.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("reportDataType", ReportDataTypeEnum.DECISION.getCode())
                .andEqualTo("reportResult", Constant.STRING_0);
        if (StrUtil.isNotEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
        }
        report.orderBy("createTime").desc();

        List<CaseDataReportRecord> caseDataReportRecords = caseDataReportRecordMapper.selectByExample(report);
        if (caseDataReportRecords == null || caseDataReportRecords.isEmpty()) {
            return false;
        }
        CaseDataReportRecord latestReportRecord = caseDataReportRecords.get(0);
        if (StrUtil.isEmpty(latestReportRecord.getPublicUrl())) {
            return false;
        }
        /*if (checkPublicUrl(latestReportRecord.getPublicUrl())) {
            return true;
        }*/
        return true;
    }



    /**
     * 获取公示信息
     *
     * @param caseId
     * @param partyIdList
     * @return
     */
    private CaseDataReportRecord getCaseReportRecordInfo(String caseId, List<String> partyIdList) {
        Example report = new Example(CaseDataReportRecord.class);
        Example.Criteria criteria = report.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("reportDataType", ReportDataTypeEnum.DECISION.getCode())
                .andEqualTo("reportResult", Constant.STRING_0);
        if (!CollectionUtils.isEmpty(partyIdList)) {
            criteria.andIn("partyId", partyIdList);
        }
        report.orderBy("createTime").desc();

        List<CaseDataReportRecord> caseDataReportRecords = caseDataReportRecordMapper.selectByExample(report);
        if (caseDataReportRecords == null || caseDataReportRecords.isEmpty()) {
            return null;
        }
       return caseDataReportRecords.get(0);
    }

    /**
     * 获取公示信息
     *
     * @param caseId
     * @param partyIdList
     * @return
     */
    private CaseDataReportStageInfo getCaseReportStageInfo(String caseId, List<String> partyIdList) {
        Example report = new Example(CaseDataReportStageInfo.class);
        Example.Criteria criteria = report.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("reportStageTag", ReportDataTypeEnum.DECISION.getCode())
                .andEqualTo("isFinishReport", Constant.STRING_1);
        if (!CollectionUtils.isEmpty(partyIdList)) {
            criteria.andIn("partyId", partyIdList);
        }
        report.orderBy("createTime").desc();

        List<CaseDataReportStageInfo> caseDataReportRecords = caseDataReportStageInfoMapper.selectByExample(report);
        if (caseDataReportRecords == null || caseDataReportRecords.isEmpty()) {
            return null;
        }
        return caseDataReportRecords.get(0);
    }

    /**
     * 校验公示地址是否存在
     *
     * @param url
     * @return
     */
    private boolean checkPublicUrl(String url) {
        String response = BaseUtil.sendGETRequest(url, new HashMap<>());
        if (ObjectUtils.isEmpty(response)) {
            return false;
        }
        return true;
    }

    /**
     * 获取当事人信息
     *
     * @param caseMainInfo
     * @param partyNameList
     * @param partyTypeMap
     */
    private void getPartyInfo(CaseMainInfo caseMainInfo, List<String> partyNameList, Map<String, String> partyTypeMap, CaseActsCodeDetailVo reVo) {
        Example partyExample = new Example(CasePartiesRecord.class);
        partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", "1");
        partyExample.orderBy("partyType").desc();
        List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
        List<CaseActsCodePartyInfoVo> partyInfoList = new ArrayList<>();

        partiesRecords.forEach(e -> {
            CaseActsCodePartyInfoVo vo = new CaseActsCodePartyInfoVo();
            vo.setPartyId(e.getPartyId());
            vo.setPartyType(e.getPartyType());
            vo.setPartyName(e.getPartyName());
            partyInfoList.add(vo);
            partyNameList.add(e.getPartyName());
            partyTypeMap.put(e.getPartyId(), e.getPartyType());
        });
        reVo.setPartyInfoList(partyInfoList);
    }

    /**
     * 获取主表信息
     *
     * @param caseMainInfo
     * @param reVo
     */
    private void setMainInfo(CaseMainInfo caseMainInfo, CaseActsCodeDetailVo reVo) {
        reVo.setCaseCurrentStageName(caseMainInfo.getCaseCurrentStageName());
        reVo.setCaseCurrentLinkName(caseMainInfo.getCaseCurrentLinkName());
        reVo.setCaseNumber(caseMainInfo.getCaseNumber());
        reVo.setCaseSource(caseMainInfo.getCaseSource());
        reVo.setCaseTypeText(CaseTypeEnum.getValueByCode(caseMainInfo.getCaseType()));
        //快办流程设置为普通程序
        if (CaseTypeEnum.SIMPLE_QUICK.getCode().equals(caseMainInfo.getCaseType())) {
            reVo.setCaseTypeText(CaseTypeEnum.NORMAL_PROCEDURE.getDes());
        }
        reVo.setCaseRegisterTime(DateUtil.format(caseMainInfo.getCaseRegistTime(), DatePattern.NORM_DATE_PATTERN));
        reVo.setCaseTimeLimit(DateUtil.format(caseMainInfo.getCaseTimelimit(), DatePattern.NORM_DATE_PATTERN));
        reVo.setCaseVerdictEndTime(DateUtil.format(caseMainInfo.getCaseVerdictEndTime(), DatePattern.NORM_DATE_PATTERN));
        reVo.setCaseEndTime(DateUtil.format(caseMainInfo.getCaseEndTime(), DatePattern.NORM_DATE_PATTERN));
        reVo.setHandleOrgName(caseMainInfo.getCaseOrgName());
        reVo.setHandleDeptName(caseMainInfo.getCaseDeptName());
        reVo.setCaseStatus(caseMainInfo.getCaseStatus());
        if(!Constant.STRING_1.equals(caseMainInfo.getCaseType())) {
            int timeLimit = BaseUtil.getBetweenDays(BaseUtil.getTodayStartDate(), DateUtil.parseDate(DateUtil.formatLocalDateTime(caseMainInfo.getCaseTimelimit())));
            this.handleRemainTimes(timeLimit, reVo);
            if (timeLimit < Constant.INTEGER_0) {
                reVo.setTimeColor("red");
            } else if (timeLimit <= Constant.INTEGER_7) {
                reVo.setTimeColor("yellow");
            } else if (timeLimit > Constant.INTEGER_7) {
                reVo.setTimeColor("blue");
            }
        }
    }

    /**
     * 获取时间
     * @param timeLimit
     * @param vo
     */
    private void handleRemainTimes(int timeLimit, CaseActsCodeDetailVo vo) {
        //办案期限
        if (timeLimit == Constant.INTEGER_0) {
            vo.setRemainTime("截止日");
        } else if (timeLimit > Constant.INTEGER_0) {
            vo.setRemainTime("剩余" + timeLimit + "天");
        } else {
            vo.setRemainTime("超" + String.valueOf(timeLimit).substring(Constant.INTEGER_1) + "天");
        }

        if (CaseStatusEnum.SUSPEND.getCode().equals(vo.getCaseStatus())) {
            vo.setRemainTime("暂停");
        }

        if (vo.getCaseVerdictEndTime() == null) {
            return;
        }
        //裁决期限
        int verdictLimit = BaseUtil.getBetweenDays(DateUtil.parseDate(vo.getCaseTimeLimit()), DateUtil.parseDate(vo.getCaseVerdictEndTime()));
        if(verdictLimit > Constant.INTEGER_0){
            vo.setRemainVerdictTime("超" + String.valueOf(verdictLimit).substring(Constant.INTEGER_1) + "天");
        }
        /*if (verdictLimit == Constant.INTEGER_0) {
            vo.setRemainVerdictTime("已到期");
        } else if (verdictLimit > Constant.INTEGER_0) {
            vo.setRemainVerdictTime("剩余" + verdictLimit + "天");
        } else {
            vo.setRemainVerdictTime("超" + String.valueOf(verdictLimit).substring(Constant.INTEGER_1) + "天");
        }*/
    }
    /**
     * //获取处罚决定信息
     *
     * @param caseMainInfo
     * @param partyTypeMap
     * @param partyNameList
     * @param reVo
     */
    private void getPunishInfoList(CaseMainInfo caseMainInfo, Map<String, String> partyTypeMap, List<String> partyNameList, CaseActsCodeDetailVo reVo) {
        //获取处罚决定信息
        List<CaseActsCodePunishDecisionInfoVo> punishInfoList = new ArrayList<>();
        //先判断是否为分别处罚，如果是分别处罚，则去补充表查询决定书文号，否则去宽表查询决定书文号，决定书日期，根据决定书文号和caseId去文书记录表查询审核通过时间
        //分别处罚
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
            auxiliaryExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
            if (auxiliaryInfoList != null && auxiliaryInfoList.size() > 0) {
                auxiliaryInfoList.forEach(e -> {
                    CaseActsCodePunishDecisionInfoVo vo = this.getPunishDecisionInfo(e.getPartyName(), partyTypeMap.get(e.getPartyId()), e.getPunishDocumentNumber(), caseMainInfo.getId());
                    vo.setPunishList(this.getPunishList(e.getPunishKinds(), e.getInvestConclusion(), e.getDraftPunishMoney(), e.getConfiscateIllegalMoney(), e.getConfiscateIllegalProperty(), e.getConfiscateIllegalPropertyValue()));
                    punishInfoList.add(vo);
                });
                //排序
                List<CaseActsCodePunishDecisionInfoVo> rePunishInfoList = punishInfoList.stream().sorted(Comparator.comparing(CaseActsCodePunishDecisionInfoVo::getPartyType).reversed()).collect(Collectors.toList());
                reVo.setPunishInfoList(rePunishInfoList);
            }
        } else {//非分别处罚
            if(!Constant.STRING_1.equals(caseMainInfo.getCaseType())) {
                CaseMainDetailInfo queryDetailParam = new CaseMainDetailInfo();
                queryDetailParam.setCaseId(caseMainInfo.getId());
                CaseMainDetailInfo detailInfo = caseMainDetailInfoMapper.selectOne(queryDetailParam);
                CaseActsCodePunishDecisionInfoVo vo = this.getPunishDecisionInfo(CollUtil.join(partyNameList, "、"), "", detailInfo.getPunishDocumentNumber(), caseMainInfo.getId());
                vo.setPunishList(this.getPunishList(detailInfo.getPunishKinds(), detailInfo.getInvestConclusion(), detailInfo.getDraftPunishMoney(), detailInfo.getConfiscateIllegalMoney(), detailInfo.getConfiscateIllegalProperty(), detailInfo.getConfiscateIllegalPropertyValue()));
                punishInfoList.add(vo);
            }else{
                CaseActsCodePunishDecisionInfoVo vo = new CaseActsCodePunishDecisionInfoVo();
                vo.setPartyName(CollUtil.join(partyNameList, "、"));
                vo.setPartyType("");
                vo.setPunishDecisionDate(caseMainInfo.getCaseCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                vo.setPunishDecisionDocumentNumber(caseMainInfo.getCaseNumber());
                punishInfoList.add(vo);
            }
            reVo.setPunishInfoList(punishInfoList);
        }
    }

    /**
     * 获取处罚事项
     *
     * @param punishKinds
     * @param investConclusion
     * @param punishMoney
     * @param illegalMoney
     * @param illegalProperty
     * @param illegalPropertyValue
     * @return
     */
    private List<String> getPunishList(String punishKinds, String investConclusion, String punishMoney, String illegalMoney, String illegalProperty, String illegalPropertyValue) {
        List<String> punishList = new ArrayList<>();
        //予以处罚
        if (Constant.STRING_1.equals(investConclusion)) {
            String[] kinds = punishKinds.split(Constant.STRING_COMMA);
            for (String kind : kinds) {
                if ("罚款".equals(kind)) {
                    punishList.add(kind + punishMoney + "元");
                } else if ("没收违法所得".equals(kind)) {
                    punishList.add(kind + illegalMoney + "元");
                } else if ("没收非法财物".equals(kind)) {
                    punishList.add(kind + "包括" + illegalProperty + "价值" + illegalPropertyValue + "元");
                } else {
                    punishList.add(kind);
                }
            }
        }
        //不予处罚
        else if (Constant.STRING_2.equals(investConclusion)) {
            punishList.add("不予处罚");
        }
        return punishList;
    }


    /**
     * 获取处罚决定信息
     *
     * @param partyName
     * @param partyType
     * @param punishDocumentNumber
     * @param caseId
     * @return
     */
    private CaseActsCodePunishDecisionInfoVo getPunishDecisionInfo(String partyName, String partyType, String punishDocumentNumber, String caseId) {
        CaseActsCodePunishDecisionInfoVo vo = new CaseActsCodePunishDecisionInfoVo();
        vo.setPartyName(partyName);
        vo.setPartyType(partyType);
        vo.setPunishDecisionDocumentNumber(punishDocumentNumber);
        vo.setPunishDecisionDate(this.getPunishDecisionDate(caseId, punishDocumentNumber));
        return vo;
    }

    /**
     * 根据案件ID和处罚决定书文号，查询处罚决定书时间
     *
     * @return
     */
    private String getPunishDecisionDate(String caseId, String punishDocumentNumber) {
        if (StrUtil.isEmpty(punishDocumentNumber)) {
            return null;
        }
        CaseDocumentRecord queryParam = new CaseDocumentRecord();
        queryParam.setCaseId(caseId);
        queryParam.setDocumentNumber(punishDocumentNumber);
        queryParam.setDocumentRecordStatus(Constant.STRING_1);
        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordMapper.selectOne(queryParam);
        if (caseDocumentRecord != null) {
            return DateUtil.format(caseDocumentRecord.getDocumentApprovalTime(), DatePattern.NORM_DATE_PATTERN);
        }
        return null;
    }

    /**
     * 获取案由
     * @param caseId
     * @return
     */
    private String getCaseReasons(String caseId) {
        List<String> caseReasons = new ArrayList<>();
        Example reasonExample = new Example(CaseReasonMainRecord.class);
        reasonExample.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
        List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(reasonExample);
        if(recordList == null || recordList.isEmpty()){
            return null;
        }
        recordList.forEach(e -> {
            caseReasons.add(e.getCaseReasonName());
        });
        return CollUtil.join(caseReasons, ";");
    }
    @Override
    public CasePublicityActsCodeVo getCasePublicityByActsCode(ActsCodeRequest dto) {
        CasePublicityActsCodeVo reVo = new CasePublicityActsCodeVo();

        //获取主表数据
        CaseMainInfo queryParam = new CaseMainInfo();
        queryParam.setCaseActsCode(dto.getActsCode());
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectOne(queryParam);
        if (caseMainInfo == null) {
            throw new BusinessException("未查询到案件信息");
        }
        List<String> currentUserPartyIdList = new ArrayList<>();
        if(StringUtils.isNotBlank(dto.getIdnum()) || StringUtils.isNotBlank(dto.getUniCode())){
            currentUserPartyIdList = getCasePartyIdsByActsCode(dto);
            reVo.setIsCaseParty(CollectionUtils.isEmpty(currentUserPartyIdList) ? Constant.STRING_0 : Constant.STRING_1);
        }else{
            reVo.setIsCaseParty(Constant.STRING_0);
        }
        reVo.setActsCode(dto.getActsCode());
        //案件名称
        reVo.setBarCodeUrl(caseMainInfo.getCaseBarCodeUrl());
        reVo.setQrCodeUrl(caseMainInfo.getCaseQrCodeUrl());
        reVo.setCaseName(caseMainInfo.getCaseName());
        reVo.setCaseCurrentStageName(caseMainInfo.getCaseCurrentStageName());
        reVo.setCaseOrgName(caseMainInfo.getCaseOrgName());
        reVo.setCaseRegisterTime(DateUtil.format(caseMainInfo.getCaseRegistTime(), DatePattern.NORM_DATE_PATTERN));
        if(CaseStatusEnum.REVOKE.getCode().equals(caseMainInfo.getCaseStatus()) ||
                CaseStatusEnum.PUNISH_REVOKE.getCode().equals(caseMainInfo.getCaseStatus())){
            reVo.setIsPub(Constant.STRING_0);
            reVo.setNoDecisionReason("案件已撤销");
            return reVo;
        }
        if(CaseStatusEnum.TERMINATE.getCode().equals(caseMainInfo.getCaseStatus())
                ||CaseStatusEnum.TRANSFERRING.getCode().equals(caseMainInfo.getCaseStatus())
                    ||CaseStatusEnum.SUSPEND.getCode().equals(caseMainInfo.getCaseStatus())){
            reVo.setIsPub(Constant.STRING_0);
            reVo.setNoDecisionReason("案件已终止");
            return reVo;
        }

        //多当事人合并处罚时使用
        List<String> partyNameList = new ArrayList<>();
        //多当事人时，当事人map集合
        Map<String, String> partyTypeMap = new HashMap<>();
        reVo.setPartyInfoList(getActsCodePartyInfo(caseMainInfo, partyNameList, partyTypeMap));
        //获取处罚决定信息
        reVo.setPunishInfoList(getActsCodePunishInfoList(reVo, caseMainInfo, partyTypeMap, partyNameList,null));
        if(StrUtil.isEmpty(reVo.getIsPub()) || Constant.STRING_0.equals(reVo.getIsPub())){
            reVo.setCaseName(this.getCaseReasons(caseMainInfo.getId()));
        }
        return reVo;
    }



    @Override
    public CaseDetailActsCodeVo getCaseDetailInfoByActsCode(ActsCodeRequest dto) {
        CaseDetailActsCodeVo reVo = new CaseDetailActsCodeVo();
        reVo.setActsCode(dto.getActsCode());
        //获取主表数据
        CaseMainInfo queryParam = new CaseMainInfo();
        queryParam.setCaseActsCode(dto.getActsCode());
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectOne(queryParam);
        //设置当前用户的当事人id
        List<String> currentUserPartyIdList = null;
        if(StringUtils.isNotBlank(dto.getIdnum()) || StringUtils.isNotBlank(dto.getUniCode())){
            currentUserPartyIdList = getCasePartyIdsByActsCode(dto);
            //reVo.setCurrentPartyIdList(currentUserPartyIdList);
            reVo.setIsCaseParty(CollectionUtils.isEmpty(currentUserPartyIdList) ? Constant.STRING_0 : Constant.STRING_1);
        }else{
            reVo.setIsCaseParty(Constant.STRING_0);
        }
        if (caseMainInfo == null) {
            throw new BusinessException("未查询到案件信息");
        }
        //案件名称
        reVo.setBarCodeUrl(caseMainInfo.getCaseBarCodeUrl());
        reVo.setQrCodeUrl(caseMainInfo.getCaseQrCodeUrl());
        reVo.setCaseName(caseMainInfo.getCaseName());
        reVo.setCaseCurrentStageName(caseMainInfo.getCaseCurrentStageName());
        reVo.setCaseOrgName(caseMainInfo.getCaseOrgName());
        reVo.setCaseRegisterTime(DateUtil.format(caseMainInfo.getCaseRegistTime(), DatePattern.NORM_DATE_PATTERN));
        //违则罚则
        List<String> caseReasons = new ArrayList<>();
        Example reasonExample = new Example(CaseReasonMainRecord.class);
        reasonExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", Constant.STRING_1);
        List<CaseReasonMainRecord> recordList = caseReasonMainRecordMapper.selectByExample(reasonExample);
        List<CaseReasonActsCodeVo> caseReasonList = new ArrayList<>();
        if(!CollectionUtils.isEmpty(recordList)){
            //违则
            String illegalBasis = recordList.stream().map(r -> r.getIllegalBasis()).collect(Collectors.joining(","));
            //罚则
            String punishBasis = recordList.stream().map(r -> r.getPunishBasis()).collect(Collectors.joining(","));
            reVo.setIllegalBasis(illegalBasis);
            reVo.setPunishBasis(punishBasis);
            recordList.forEach(mainRecord ->{
                CaseReasonActsCodeVo caseReasonItem = new CaseReasonActsCodeVo();
                caseReasonItem.setCaseReasonId(mainRecord.getId());
                //处罚事项
                caseReasonItem.setCaseReason(mainRecord.getCaseReasonName());
                //违则
                caseReasonItem.setIllegalBasis(mainRecord.getIllegalBasis());
                //违则详情
                caseReasonItem.setIllegalDetail(mainRecord.getIllegalDetail());
                //罚则
                caseReasonItem.setPunishBasis(mainRecord.getPunishBasis());
                //罚则详情
                caseReasonItem.setPunishDetail(mainRecord.getPunishDetail());
                //裁量标准
                //caseReasonItem.setDiscretionInterval(mainRecord.getCaseReasonName());
                caseReasonList.add(caseReasonItem);
            });
            reVo.setCaseReasonList(caseReasonList);
        }

       /* //处罚决定信息
        List<CasePublicInfoListVo> punishDecisionDocuments = caseMainInfoMapper.getCasePunishDocuments(caseMainInfo.getId());
        List<CasePublicInfoListVo> reList = new ArrayList<>();
        //如果没有查出数据，则返回
        if (punishDecisionDocuments == null || punishDecisionDocuments.isEmpty()) {
            reVo.setNoDecisionReason("案件处罚决定暂未做出");
            return reVo;
        }*/
        //多当事人合并处罚时使用
        List<String> partyNameList = new ArrayList<>();
        //多当事人时，当事人map集合
        Map<String, String> partyTypeMap = new HashMap<>();
        reVo.setPartyInfoList(getActsCodePartyInfo(caseMainInfo, partyNameList, partyTypeMap));
        //获取处罚决定信息
        List<CasePunishDecisionVo> punishInfoList= getCaseDetailActsCodePunishInfoList(reVo, caseMainInfo, partyTypeMap, partyNameList,reVo.getCaseReasonList(), dto.getIdnum());
        reVo.setPunishInfoList(punishInfoList);
        /*//获取案件文书信息
        List<CaseActsCodeDocVo> docDocuments = caseMainInfoMapper.getNeedSentDocuments(caseMainInfo.getId());*/
        //当事人情况
        if(Constant.STRING_1.equals(reVo.getIsCaseParty())){
            List<String> finalCurrentUserPartyIdList = currentUserPartyIdList;
            //未做出处罚决定前，没有值
            if(ObjectUtil.isNotEmpty(punishInfoList)){
                List<CasePunishDecisionVo> fiterPunishInfoList = punishInfoList.stream().filter(p -> StringUtils.isBlank(p.getPartyId())
                        || (StringUtils.isNotBlank(p.getPartyId()) && finalCurrentUserPartyIdList.contains(p.getPartyId()))).collect(Collectors.toList());
                reVo.setPunishInfoList(fiterPunishInfoList);
            }
            /*List<CaseActsCodeDocVo> fiterDocList = new ArrayList<>();
            for (CaseActsCodeDocVo doc : docDocuments) {
                //判断文书优先级 签字》印章》原始文件
                if(StringUtils.isNotBlank(doc.getDocumentUrlAfterSign())){
                    doc.setDocumentUrl(doc.getDocumentUrlAfterSign());
                }else if(StringUtils.isNotBlank(doc.getDocumentUrlAfterSeal())){
                    doc.setDocumentUrl(doc.getDocumentUrlAfterSeal());
                }
                if(StringUtils.isBlank(doc.getPartyId())){
                    //未空情况，属于共有文书
                    fiterDocList.add(doc);
                }else{
                    List<String> copyPartyIdList =new ArrayList<>();
                    copyPartyIdList.addAll(currentUserPartyIdList);
                    copyPartyIdList.retainAll(Arrays.asList(doc.getPartyId().split(",")));
                    if(copyPartyIdList.size()>0){
                        fiterDocList.add(doc);
                    }
                }
            }
            reVo.setDocList(fiterDocList);*/
            //查询评价信息
            Example evaluateExample = new Example(EvaluateRecord.class);
            evaluateExample.createCriteria()
                    .andEqualTo("evaluateZjhm", StringUtils.isNoneBlank(dto.getIdnum())?dto.getIdnum():dto.getUniCode())
                    .andEqualTo("actionCode", dto.getActsCode());
            List<EvaluateRecord> evaluateList = evaluateRecordMapper.selectByExample(evaluateExample);
            if(!CollectionUtils.isEmpty(evaluateList)){
                EvaluateInfoVo evaluateInfoVo = new EvaluateInfoVo();
                BeanUtils.copyProperties(evaluateList.get(0),evaluateInfoVo);
                reVo.setEvaluateInfo(evaluateInfoVo);
            }
            //获取案件进度
            //setCaseProgress(reVo,caseMainInfo, finalCurrentUserPartyIdList);
        }else{
            reVo.getPunishInfoList().forEach(p->{
                PaymentPromptVo paymentPrompt = p.getPaymentPrompt();
                if(!ObjectUtils.isEmpty(paymentPrompt)){
                    paymentPrompt.setNoticeNo(null);
                    paymentPrompt.setPayStatus(null);
                    paymentPrompt.setPayMoney(null);
                    paymentPrompt.setInvoiceUrl(null);
                    paymentPrompt.setPayUrl(null);
                }
            });
        }

        //设置当前用户
        /*if(StringUtils.isNotBlank(dto.getIdnum()) || StringUtils.isNotBlank(dto.getUniCode())){
            reVo.setCurrentPartyIdList(getCasePartyIdsByActsCode(dto));
        }*/
        return reVo;
    }

    /**
     * 获取案件进度
     * @param caseMainInfo
     * @param partyIdList
     * @return
     */
    private void setCaseProgress(CaseDetailActsCodeVo caseDetailActsCodeVo, CaseMainInfo caseMainInfo, List<String> partyIdList) {
        CaseProgressEnum caseProgressEnum = null;
        String content = null;
        String caseStatus = caseMainInfo.getCaseStatus();
        if (Constant.INTEGER_3.equals(caseStatus)) {
            caseProgressEnum = CaseProgressEnum.JA;
        }
        String caseCurrentStageCode = caseMainInfo.getCaseCurrentStageCode();
        if ("CLOSE_ARCHIVING".equals(caseCurrentStageCode) && !Constant.INTEGER_3.equals(caseStatus)) {
            caseProgressEnum = CaseProgressEnum.JA;
            content = "您的案件正在结案中";
        } else if ("INVESTIGATION".equals(caseCurrentStageCode)) {
            caseProgressEnum = CaseProgressEnum.DCQZ;
        } else if ("PUNISH_INFORM".equals(caseCurrentStageCode)) {
            List<CaseAcsPublicInfoListVo> cfgzs = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("CFGZS","CFGZSTZL","DK2BYXZCFGZS"), partyIdList);
            //分别处罚,以最慢的那条为准
            if(HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())){
                if(cfgzs.size() == 1){//只有一条记录，代表最慢的还在调查取证
                    caseProgressEnum = CaseProgressEnum.DCQZ;
                }else {//否则循环拿取最慢的一条记录
                    //是否未送达
                    boolean isExistWsd = false;
                    CaseAcsPublicInfoListVo vo = new CaseAcsPublicInfoListVo();
                    for(CaseAcsPublicInfoListVo item : cfgzs){
                        //送达标记
                        if(!DocumentStatusEnum.SENT.getCode().equals(item.getDocumentSentStatus())){
                            isExistWsd = true;
                            vo = item;
                            break;
                        }
                    }
                    if(isExistWsd){
                        caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_WSD;
                    }else {
                        caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                    }
                }
            }else {
                if(CollectionUtils.isEmpty(cfgzs)){
                    caseProgressEnum = CaseProgressEnum.DCQZ;
                }else {//如果有记录
                    CaseAcsPublicInfoListVo vo = cfgzs.get(0);
                    if(!DocumentStatusEnum.CHECK_END.getCode().equals(vo.getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else if(DocumentStatusEnum.SENT.getCode().equals(vo.getDocumentSentStatus())){//如果是审批送达状态，则是送达
                        //判断是否为不予处罚
                        if("DK2BYXZCFGZS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFGZ_SD;
                        }
                    }else {//否则则是未送达
                        //判断是否为不予处罚
                        if("DK2BYXZCFGZS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_WSD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFGZ_WSD;
                        }
                    }
                }
            }



            if(HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())){//分别处罚
                if(CollectionUtils.isEmpty(cfgzs)){
                    //判断是否为不予处罚
                    List<CaseAcsPublicInfoListVo> bycfgzs = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("DK2BYXZCFGZS"), partyIdList);
                    if(ObjectUtil.isEmpty(bycfgzs)){
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else if(!DocumentStatusEnum.CHECK_END.getCode().equals(bycfgzs.get(0).getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else if(DocumentStatusEnum.SENT.getCode().equals(bycfgzs.get(0).getDocumentSentStatus())){
                        caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                    } else {
                        caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_WSD;
                    }
                }else {//查询有值的话，如果和当事人的list不相等，则代表有最慢的还在调查取证，如果有两条，判断最慢的那条
                    if(cfgzs.size() != partyIdList.size()){//只有一条记录，代表最慢的还在调查取证
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else {//否则循环拿取最慢的一条记录
                        boolean isExistWsd = false;
                        for(CaseAcsPublicInfoListVo vo : cfgzs){
                            //送达标记
                            if(!DocumentStatusEnum.SENT.getCode().equals(vo.getDocumentSentStatus())){
                                isExistWsd = true;
                                break;
                            }
                        }
                        if(isExistWsd){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_WSD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                        }
                    }
                }
            }else {
                if(CollectionUtils.isEmpty(cfgzs)){
                    //判断是否为不予处罚
                    List<CaseAcsPublicInfoListVo> bycfgzs = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("DK2BYXZCFGZS"), partyIdList);
                    if(ObjectUtil.isEmpty(bycfgzs)){
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else if(!DocumentStatusEnum.CHECK_END.getCode().equals(bycfgzs.get(0).getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else if(DocumentStatusEnum.SENT.getCode().equals(bycfgzs.get(0).getDocumentSentStatus())){
                        caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                    } else {
                        caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_WSD;
                    }
                }else if (!DocumentStatusEnum.CHECK_END.getCode().equals(cfgzs.get(0).getDocumentApprovalStatus())) {//如果不是审批通过状态，则还是上一个阶段
                    caseProgressEnum = CaseProgressEnum.DCQZ;
                }else if (DocumentStatusEnum.SENT.getCode().equals(cfgzs.get(0).getDocumentSentStatus())) {
                    caseProgressEnum = CaseProgressEnum.CFGZ_SD;
                } else {
                    caseProgressEnum = CaseProgressEnum.CFGZ_WSD;
                }
            }
        } else if ("PUNISH_DECIDE".equals(caseCurrentStageCode)) {
            List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("CFJDS"), partyIdList);
            if(CollectionUtils.isEmpty(cfjds)){
                List<CaseAcsPublicInfoListVo> bycfjds = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("BYCFJDS"), partyIdList);
                if(ObjectUtil.isEmpty(bycfjds)){
                    caseProgressEnum = CaseProgressEnum.CFGZ_SD;
                }else if(!DocumentStatusEnum.CHECK_END.getCode().equals(bycfjds.get(0).getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                    caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                }else if(bycfjds.get(0).getDocumentSentStatus().equals("SEND_1")){
                    caseProgressEnum = CaseProgressEnum.BYCF_CFJD_SD;
                }else {
                    caseProgressEnum = CaseProgressEnum.BYCF_CFJD_WSD;
                }
            }else if(!DocumentStatusEnum.CHECK_END.getCode().equals(cfjds.get(0).getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                caseProgressEnum = CaseProgressEnum.CFGZ_SD;
            }else if(cfjds.get(0).getDocumentSentStatus().equals("SEND_1")){
                caseProgressEnum = CaseProgressEnum.CFJD_SD;
            }else {
                caseProgressEnum = CaseProgressEnum.CFJD_WSD;
            }
        } else if ("PUNISH_EXECUTION".equals(caseCurrentStageCode)) {
            List<CaseActsCodePayInfoVo> payVoList = casePaymentMainRecordMapper.getPayInfo(caseMainInfo.getId(), partyIdList);
            if (!CollectionUtils.isEmpty(payVoList)) {
                CaseActsCodePayInfoVo payInfoVo = payVoList.get(0);
                if(StringUtils.isBlank(payInfoVo.getPayStatus())){
                    caseProgressEnum = CaseProgressEnum.CFJD_SD;
                }else if (Arrays.asList("1", "3").contains(payInfoVo.getPayStatus())) {
                    caseProgressEnum = CaseProgressEnum.JKWC;
                } else {
                    List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("CFJDS"), partyIdList);
                    if (!CollectionUtils.isEmpty(cfjds) && cfjds.get(0).getSentTime() != null) {
                        LocalDate expiredPayDate = cfjds.get(0).getSentTime().toLocalDate().plusDays(15);
                        Map<String, String> valueMap = new HashMap<>(1);
                        StringSubstitutor ss = new StringSubstitutor();
                        if (LocalDate.now().isAfter(expiredPayDate)) {
                            valueMap.put("overDueDay", LocalDate.now().toEpochDay() - expiredPayDate.toEpochDay() + "");
                            content = CaseProgressEnum.YQ_WJK.getContent();
                            caseProgressEnum = CaseProgressEnum.YQ_WJK;
                        } else {
                            valueMap.put("expiredPayDate", expiredPayDate.format(DateTimeFormatter.ofPattern(DatePattern.CHINESE_DATE_PATTERN)));
                            content = CaseProgressEnum.WJK.getContent();
                            caseProgressEnum = CaseProgressEnum.WJK;
                        }
                        ss.setVariableResolver(StringLookupFactory.INSTANCE.mapStringLookup(valueMap));
                        content = ss.replace(content);
                    }
                }
            }
        }
        if (caseProgressEnum != null) {
            caseDetailActsCodeVo.setCaseProgressCode(caseProgressEnum.getCode());
            caseDetailActsCodeVo.setCaseProgress(StringUtils.isNotBlank(content) ? content : caseProgressEnum.getContent());
        }
    }


    /**
     * 获取案件阶段
     * @param notPunishVo
     * @param caseMainInfo
     * @param partyId
     */
    private void getCaseProgress(CasePunishDecisionVo notPunishVo, CaseMainInfo caseMainInfo, String partyId){
        CaseProgressEnum caseProgressEnum = null;
        String content = null;
        String caseStatus = caseMainInfo.getCaseStatus();
        if (Constant.INTEGER_3.equals(caseStatus)) {
            caseProgressEnum = CaseProgressEnum.JA;
        }
        //获取当前阶段
        Example example = new Example(WorkFlowRollSubMainInfo.class);
        Example.Criteria criteria = example.createCriteria().andEqualTo("workId", caseMainInfo.getId());
        if(StrUtil.isNotEmpty(partyId)){
            criteria.andEqualTo("workSubId", partyId);
        }
        List<WorkFlowRollSubMainInfo> flowList = workFlowRollSubMainInfoMapper.selectByExample(example);
        if(ObjectUtil.isNotEmpty(flowList)){
            String caseCurrentStageCode = flowList.get(0).getWorkCurrentStageCode();
            if ("CLOSE_ARCHIVING".equals(caseCurrentStageCode) && !Constant.INTEGER_3.equals(caseStatus)) {
                caseProgressEnum = CaseProgressEnum.JA;
                content = "您的案件正在结案中";
            } else if ("INVESTIGATION".equals(caseCurrentStageCode)) {
                caseProgressEnum = CaseProgressEnum.DCQZ;
            } else if ("PUNISH_INFORM".equals(caseCurrentStageCode)) {
                List<CaseAcsPublicInfoListVo> cfgzs = caseMainInfoMapper.getCaseDocByKindCodeAndPartyId(caseMainInfo.getId(), Arrays.asList("CFGZS","CFGZSTZL", "DK2BYXZCFGZS"), partyId);
                if(ObjectUtil.isEmpty(cfgzs)){
                    caseProgressEnum = CaseProgressEnum.DCQZ;
                }else {
                    CaseAcsPublicInfoListVo vo = cfgzs.get(0);
                    if(!DocumentStatusEnum.CHECK_END.getCode().equals(vo.getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                        caseProgressEnum = CaseProgressEnum.DCQZ;
                    }else if(DocumentStatusEnum.SENT.getCode().equals(vo.getDocumentSentStatus())){
                        if("DK2BYXZCFGZS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFGZ_SD;
                        }
                    }else {
                        if("DK2BYXZCFGZS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_WSD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFGZ_WSD;
                        }
                    }
                }
            } else if ("PUNISH_DECIDE".equals(caseCurrentStageCode)) {
                List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCaseDocByKindCodeAndPartyId(caseMainInfo.getId(), Arrays.asList("CFJDS","BYCFJDS"), partyId);
                if(ObjectUtil.isEmpty(cfjds)){
                    caseProgressEnum = CaseProgressEnum.CFGZ_SD;
                }else {
                    CaseAcsPublicInfoListVo vo = cfjds.get(0);
                    if(!DocumentStatusEnum.CHECK_END.getCode().equals(vo.getDocumentApprovalStatus())){//如果不是审批通过状态，则还是上一个阶段
                        if("BYCFJDS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFGZ_SD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFGZ_SD;
                        }
                    }else if(DocumentStatusEnum.SENT.getCode().equals(vo.getDocumentSentStatus())){
                        if("BYCFJDS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFJD_SD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFJD_SD;
                        }
                    }else {
                        if("BYCFJDS".equals(vo.getDocumentKindCode())){
                            caseProgressEnum = CaseProgressEnum.BYCF_CFJD_WSD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFJD_WSD;
                        }
                    }
                }
            } else if ("PUNISH_EXECUTION".equals(caseCurrentStageCode)) {
                List<CaseActsCodePayInfoVo> payVoList = casePaymentMainRecordMapper.getPayInfo(caseMainInfo.getId(), Arrays.asList(partyId));
                if (!CollectionUtils.isEmpty(payVoList)) {
                    CaseActsCodePayInfoVo payInfoVo = payVoList.get(0);
                    if(StringUtils.isBlank(payInfoVo.getPayStatus())){
                        caseProgressEnum = CaseProgressEnum.CFJD_SD;
                    }else if (Arrays.asList("1", "3").contains(payInfoVo.getPayStatus())) {
                        caseProgressEnum = CaseProgressEnum.JKWC;
                    } else {
                        List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("CFJDS", "JYCXCFJDS"), Arrays.asList(partyId));
                        if (!CollectionUtils.isEmpty(cfjds) && cfjds.get(0).getSentTime() != null) {
                            LocalDate expiredPayDate = cfjds.get(0).getSentTime().toLocalDate().plusDays(15);
                            Map<String, String> valueMap = new HashMap<>(1);
                            StringSubstitutor ss = new StringSubstitutor();
                            if (LocalDate.now().isAfter(expiredPayDate)) {
                                valueMap.put("overDueDay", LocalDate.now().toEpochDay() - expiredPayDate.toEpochDay() + "");
                                content = CaseProgressEnum.YQ_WJK.getContent();
                                caseProgressEnum = CaseProgressEnum.YQ_WJK;
                            } else {
                                valueMap.put("expiredPayDate", expiredPayDate.format(DateTimeFormatter.ofPattern(DatePattern.CHINESE_DATE_PATTERN)));
                                content = CaseProgressEnum.WJK.getContent();
                                caseProgressEnum = CaseProgressEnum.WJK;
                            }
                            ss.setVariableResolver(StringLookupFactory.INSTANCE.mapStringLookup(valueMap));
                            content = ss.replace(content);
                        }
                    }
                }else if(Constant.STRING_1.equals(caseMainInfo.getCaseType())){//简易程序，没有支付信息
                    List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCaseDocByKindCodeAndPartyId(caseMainInfo.getId(), Arrays.asList("JYCXCFJDS"), partyId);
                    if(CollUtil.isNotEmpty(cfjds)){
                        CaseAcsPublicInfoListVo vo = cfjds.get(0);
                        if(DocumentStatusEnum.SENT.getCode().equals(vo.getDocumentSentStatus())){
                            caseProgressEnum = CaseProgressEnum.CFJD_SD;
                        }else {
                            caseProgressEnum = CaseProgressEnum.CFJD_WSD;
                        }
                    }
                }
            }
            if (caseProgressEnum != null) {
                notPunishVo.setCaseProgressCode(caseProgressEnum.getCode());
                notPunishVo.setCaseProgress(StringUtils.isNotBlank(content) ? content : caseProgressEnum.getContent());
            }
        }
        if(Constant.STRING_1.equals(caseMainInfo.getCaseType())){
            String caseCurrentStageCode = caseMainInfo.getCaseCurrentStageCode();
            if ("PUNISH_EXECUTION".equals(caseCurrentStageCode)) {
                List<CaseActsCodePayInfoVo> payVoList = casePaymentMainRecordMapper.getPayInfo(caseMainInfo.getId(), Arrays.asList(partyId));
                if (!CollectionUtils.isEmpty(payVoList)) {
                    CaseActsCodePayInfoVo payInfoVo = payVoList.get(0);
                    if(StringUtils.isBlank(payInfoVo.getPayStatus())){
                        caseProgressEnum = CaseProgressEnum.CFJD_SD;
                    }else if (Arrays.asList("1", "3").contains(payInfoVo.getPayStatus())) {
                        caseProgressEnum = CaseProgressEnum.JKWC;
                    } else {
                        List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("JYCXCFJDS"), Arrays.asList(partyId));
                        if (!CollectionUtils.isEmpty(cfjds) && cfjds.get(0).getSentTime() != null) {
                            LocalDate expiredPayDate = cfjds.get(0).getSentTime().toLocalDate().plusDays(15);
                            Map<String, String> valueMap = new HashMap<>(1);
                            StringSubstitutor ss = new StringSubstitutor();
                            if (LocalDate.now().isAfter(expiredPayDate)) {
                                valueMap.put("overDueDay", LocalDate.now().toEpochDay() - expiredPayDate.toEpochDay() + "");
                                content = CaseProgressEnum.YQ_WJK.getContent();
                                caseProgressEnum = CaseProgressEnum.YQ_WJK;
                            } else {
                                valueMap.put("expiredPayDate", expiredPayDate.format(DateTimeFormatter.ofPattern(DatePattern.CHINESE_DATE_PATTERN)));
                                content = CaseProgressEnum.WJK.getContent();
                                caseProgressEnum = CaseProgressEnum.WJK;
                            }
                            ss.setVariableResolver(StringLookupFactory.INSTANCE.mapStringLookup(valueMap));
                            content = ss.replace(content);
                        }
                    }
                }else {//简易程序，没有支付信息
                    List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCaseDocByKindCodeAndPartyId(caseMainInfo.getId(), Arrays.asList("JYCXCFJDS"), partyId);
                    if(CollUtil.isNotEmpty(cfjds)){
                        caseProgressEnum = CaseProgressEnum.CFJD_SD;
                    }
                }
            }
            if (caseProgressEnum != null) {
                notPunishVo.setCaseProgressCode(caseProgressEnum.getCode());
                notPunishVo.setCaseProgress(StringUtils.isNotBlank(content) ? content : caseProgressEnum.getContent());
            }
        }
    }

    /**
     * //获取处罚决定信息
     *
     * @param caseMainInfo
     * @param partyTypeMap
     * @param partyNameList
     */
    private List<CasePunishDecisionVo> getCaseDetailActsCodePunishInfoList(CaseDetailActsCodeVo reVo, CaseMainInfo caseMainInfo, Map<String, String> partyTypeMap, List<String> partyNameList,List<CaseReasonActsCodeVo> caseReasonList, String idNum) {
        //获取处罚决定信息
        List<CasePunishDecisionVo> punishInfoList = new ArrayList<>();
        //查询案件文书信息
        List<CaseActsCodeDocVo> docDocuments = caseMainInfoMapper.getNeedSentDocuments(caseMainInfo.getId());
        for (CaseActsCodeDocVo doc : docDocuments) {
            //判断文书优先级 签字》印章》原始文件
            if(StringUtils.isNotBlank(doc.getDocumentUrlAfterSign())){
                doc.setDocumentUrl(doc.getDocumentUrlAfterSign());
            }else if(StringUtils.isNotBlank(doc.getDocumentUrlAfterSeal())){
                doc.setDocumentUrl(doc.getDocumentUrlAfterSeal());
            }
        }
        //先判断是否为分别处罚，如果是分别处罚，则去补充表查询决定书文号，否则去宽表查询决定书文号，决定书日期，根据决定书文号和caseId去文书记录表查询审核通过时间
        //分别处罚
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            //只查询当事人是自己的信息（通过入参idnum），特殊情况处理：如果两个当事人，公司和个人，如果法人是自己，另外一个当事人也是自己，则都需要展示
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = CollUtil.newArrayList();
            if(StrUtil.isNotEmpty(idNum)){
                auxiliaryInfoList = this.getAuxiliaryInfoList(reVo, caseMainInfo.getId(), idNum);
            }else {
                Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
                auxiliaryExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId());
                auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
            }
            if (auxiliaryInfoList != null && auxiliaryInfoList.size() > 0) {
                for(CaseMainDetailAuxiliaryInfo e : auxiliaryInfoList){
                    //未做出处罚决定前，需要查询的信息
                    CasePunishDecisionVo notPunishVo = new CasePunishDecisionVo();
                    //当事人信息
                    notPunishVo.setPartyType(partyTypeMap.get(e.getPartyId()));
                    notPunishVo.setPartyId(e.getPartyId());
                    notPunishVo.setPartyName(e.getPartyName());
                    //获取文书信息
                    List<CaseActsCodeDocVo> docList = new ArrayList<>();
                    for (CaseActsCodeDocVo doc : docDocuments) {
                        if(e.getPartyId().equals(doc.getPartyId())){
                            docList.add(doc);
                        }
                    }
                    notPunishVo.setDocList(docList);
                    //获取案件进度
                    this.getCaseProgress(notPunishVo, caseMainInfo, e.getPartyId());
                    boolean isSendDecision = isSendDecision(caseMainInfo.getId(), e.getPartyId());
                    if(!isSendDecision){//决定书未送达，直接跳过
                        punishInfoList.add(notPunishVo);
                        continue;
                    }
                    //如果已做出决定（处罚和不予处罚：默认不公示）
                    CasePunishDecisionVo vo = this.getActsCodeCasePunishDecisionVo(e.getPartyName(), e.getPartyId(),partyTypeMap.get(e.getPartyId()), e.getPunishDocumentNumber(), caseMainInfo.getId());
                    vo.setDocList(notPunishVo.getDocList());
                    vo.setCaseProgress(notPunishVo.getCaseProgress());
                    vo.setCaseProgressCode(notPunishVo.getCaseProgressCode());
                    if(Constant.STRING_1.equals(e.getIsPublicity())){
                        vo.setPunishList(this.getPunishList(e.getPunishKinds(), e.getInvestConclusion(), e.getDraftPunishMoney(), e.getConfiscateIllegalMoney(), e.getConfiscateIllegalProperty(), e.getConfiscateIllegalPropertyValue()));
                        //获取缴款信息 过滤失效缴款
                        vo.setCaseReasonId(e.getCaseReasonId());
                        //获取公示内容
                        vo.setDecisionContent(e.getPublicityContent());
                        if(!CollectionUtils.isEmpty(caseReasonList)) {
                            caseReasonList.forEach(caseReason->{
                                if(caseReason.getCaseReasonId().equals(e.getCaseReasonId())){
                                    caseReason.setDiscretionInterval(e.getDiscretionInterval());
                                }
                            });
                        }
                        //如果是处罚的话，才展示缴款信息
                        if(Constant.STRING_1.equals(e.getInvestConclusion())){
                            setPayMentInfo(caseMainInfo,vo,Arrays.asList(e.getPartyId()));
                            PaymentPromptVo paymentPrompt = vo.getPaymentPrompt();
                            if(paymentPrompt!=null){
                                paymentPrompt.setDraftPunishMoney(e.getDraftPunishMoney());
                                paymentPrompt.setConfiscateIllegalMoney(e.getConfiscateIllegalMoney());
                            }
                        }
                        //公示信息
                        if(e.getIsPublicity().equals("1")){
                            //CaseDataReportRecord caseReportRecordInfo = getCaseReportRecordInfo(caseMainInfo.getId(), Arrays.asList(e.getPartyId()));
                            CaseDataReportStageInfo stageInfo = getCaseReportStageInfo(caseMainInfo.getId(), Arrays.asList(e.getPartyId()));
                            LocalDateTime publicDate = this.getPublicDate(caseMainInfo.getId(), e.getPartyId());
                            int publicityStatus = stageInfo == null ? Constant.INTEGER_0 : LocalDateTime.now().isAfter(publicDate) ? Constant.INTEGER_1 : Constant.INTEGER_0;
                            //只有处罚的情况下，才有公示信息
                            if(Constant.STRING_1.equals(e.getInvestConclusion())){
                                vo.setPublicityInfo(CaseActsPublicityInfoVo.builder()
                                        .publicityContent(e.getPublicityContent())
                                        .publicityDate(stageInfo == null ? null : publicDate)
                                        .publicityStatus(publicityStatus)
                                        //默认3年
                                        .publicityTerm("3年")
                                        .build());
                            }
                        }
                    }else {//不公示
                        vo.setPublicityInfo(CaseActsPublicityInfoVo.builder().publicityStatus(Constant.INTEGER_0 ).build());
                    }
                    //救济提示
                    SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), null);
                    vo.setReliefTip(
                            "如不服本处罚决定，可以在收到本决定书之日起 60 日内向" +
                                    sysDepartParam.getAdministrativeGovName() +
                                    "申请行政复议；也可以在收到本决定书之日起 6 个月内直接向" +
                                    sysDepartParam.getAdministrativeActionCourtName() +
                                    "起诉，但本决定不停止执行，法律另有规定的除外。逾期不申请行政" +
                                    "复议、不提起行政诉讼又不履行的，本机关将依法申请人民法院强制执行或" +
                                    "者依照有关规定强制执行。"
                    );
                    //如果是不予处罚的话
                    if(Constant.STRING_2.equals(e.getInvestConclusion())){
                        vo.setNotGivePunishReason(CaseNotGivePunishReasonEnum.getDescByCode(e.getNotGivePunishReason()));
                    }
                    vo.setInvestConclusion(e.getInvestConclusion());
                    punishInfoList.add(vo);
                }
                //排序
                List<CasePunishDecisionVo> rePunishInfoList = punishInfoList.stream().sorted(Comparator.comparing(CasePunishDecisionVo::getPartyType).reversed()).collect(Collectors.toList());
                return rePunishInfoList;
            }
        } else {//非分别处罚
            if(!Constant.STRING_1.equals(caseMainInfo.getCaseType())) {
                CaseMainDetailInfo queryDetailParam = new CaseMainDetailInfo();
                queryDetailParam.setCaseId(caseMainInfo.getId());
                CaseMainDetailInfo detailInfo = caseMainDetailInfoMapper.selectOne(queryDetailParam);
                //未做出处罚决定前，需要查询的信息
                CasePunishDecisionVo notPunishVo = new CasePunishDecisionVo();
                notPunishVo.setPartyName(CollUtil.join(partyNameList, "、"));
                notPunishVo.setDocList(docDocuments);
                //获取案件进度
                this.getCaseProgress(notPunishVo, caseMainInfo, "");
                //返回true，代表已经有处罚决定书（处罚和不予处罚）做出了，并且送达了
                boolean isSendDecision = isSendDecision(caseMainInfo.getId(), "");
                if(!isSendDecision){//处罚决定未做出
                    punishInfoList.add(notPunishVo);
                    return punishInfoList;
                }
                //如果已做出决定（处罚和不予处罚：默认不公示）
                CasePunishDecisionVo vo = this.getActsCodeCasePunishDecisionVo(CollUtil.join(partyNameList, "、"),"", "", detailInfo.getPunishDocumentNumber(), caseMainInfo.getId());
                vo.setDocList(docDocuments);
                vo.setCaseProgress(notPunishVo.getCaseProgress());
                vo.setCaseProgressCode(notPunishVo.getCaseProgressCode());
                if(Constant.STRING_1.equals(detailInfo.getIsPublicity())){
                    if(Constant.STRING_1.equals(detailInfo.getInvestConclusion())){
                        //获取缴款信息 过滤失效缴款
                        setPayMentInfo(caseMainInfo,vo,null);
                        PaymentPromptVo paymentPrompt = vo.getPaymentPrompt();
                        if(paymentPrompt!=null){
                            paymentPrompt.setDraftPunishMoney(detailInfo.getDraftPunishMoney());
                            paymentPrompt.setConfiscateIllegalMoney(detailInfo.getConfiscateIllegalMoney());
                        }
                    }
                    vo.setDiscretionInterval(detailInfo.getDiscretionInterval());
                    vo.setDecisionContent(detailInfo.getPublicityContent());
                    //公示信息
                    if(detailInfo.getIsPublicity().equals("1")){
                        //CaseDataReportRecord caseReportRecordInfo = getCaseReportRecordInfo(caseMainInfo.getId(), Arrays.asList(e.getPartyId()));
                        CaseDataReportStageInfo stageInfo = getCaseReportStageInfo(caseMainInfo.getId(), null);
                        LocalDateTime publicDate = this.getPublicDate(caseMainInfo.getId(), "");
                        int publicityStatus = stageInfo == null ? Constant.INTEGER_0 : LocalDateTime.now().isAfter(publicDate) ? Constant.INTEGER_1 : Constant.INTEGER_0;
                        //只有处罚的情况下，才有公示信息
                        if(Constant.STRING_1.equals(detailInfo.getInvestConclusion())){
                            vo.setPublicityInfo(CaseActsPublicityInfoVo.builder()
                                    .publicityContent(detailInfo.getPublicityContent())
                                    .publicityDate(stageInfo == null ? null : publicDate)
                                    .publicityStatus(publicityStatus)
                                    //默认3年
                                    .publicityTerm("3年")
                                    .build());
                        }
                    }
                    if(!CollectionUtils.isEmpty(caseReasonList)) {
                        caseReasonList.forEach(caseReason->{
                            caseReason.setDiscretionInterval(detailInfo.getDiscretionInterval());
                        });
                    }
                }else {//不公示
                    vo.setPublicityInfo(CaseActsPublicityInfoVo.builder().publicityStatus(Constant.INTEGER_0 ).build());
                }
                //救济提示
                SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), null);
                vo.setReliefTip(
                        "如不服本处罚决定，可以在收到本决定书之日起 60 日内向" +
                                sysDepartParam.getAdministrativeGovName() +
                                "申请行政复议；也可以在收到本决定书之日起 6 个月内直接向" +
                                sysDepartParam.getAdministrativeActionCourtName() +
                                "起诉，但本决定不停止执行，法律另有规定的除外。逾期不申请行政" +
                                "复议、不提起行政诉讼又不履行的，本机关将依法申请人民法院强制执行或" +
                                "者依照有关规定强制执行。"
                );
                vo.setPunishList(this.getPunishList(detailInfo.getPunishKinds(), detailInfo.getInvestConclusion(), detailInfo.getDraftPunishMoney(), detailInfo.getConfiscateIllegalMoney(), detailInfo.getConfiscateIllegalProperty(), detailInfo.getConfiscateIllegalPropertyValue()));
                //如果是不予处罚的话
                if(Constant.STRING_2.equals(detailInfo.getInvestConclusion())){
                    vo.setNotGivePunishReason(CaseNotGivePunishReasonEnum.getDescByCode(detailInfo.getNotGivePunishReason()));
                }
                vo.setInvestConclusion(detailInfo.getInvestConclusion());
                punishInfoList.add(vo);
            } else {
                CaseMainDetailSimpleInfo queryParam = new CaseMainDetailSimpleInfo();
                queryParam.setCaseId(caseMainInfo.getId());
                CaseMainDetailSimpleInfo simpleInfo = caseMainDetailSimpleInfoMapper.selectOne(queryParam);

                CasePunishDecisionVo vo = new CasePunishDecisionVo();
                vo.setPartyName(CollUtil.join(partyNameList, "、"));
                vo.setPartyType("");
                List<String> punishList = new ArrayList<>();
                //不予处罚：没有决定书，不需要缴款
                if(Constant.STRING_2.equals(simpleInfo.getInvestConclusion())){
                    vo.setNotGivePunishReason(CaseNotGivePunishReasonEnum.getDescByCode(simpleInfo.getNotGivePunishReason()));
                    punishList.add("不予处罚");
                }else {
                    //处罚种类
                    String[] kinds = simpleInfo.getPunishKinds().split(Constant.STRING_COMMA);
                    for (String kind : kinds) {
                        if ("罚款".equals(kind)) {
                            punishList.add(kind + simpleInfo.getDraftPunishMoney() + "元");
                        } else {
                            punishList.add(kind);
                        }
                    }
                    //获取缴款信息 过滤失效缴款
                    setPayMentInfo(caseMainInfo,vo,null);
                    PaymentPromptVo paymentPrompt = vo.getPaymentPrompt();
                    if(paymentPrompt!=null){
                        paymentPrompt.setDraftPunishMoney(simpleInfo.getDraftPunishMoney());
                    }
                    vo.setDecisionContent(simpleInfo.getIllegalFact());
                    vo.setDocumentNumber(caseMainInfo.getCaseNumber());
                    vo.setPunishDecisionDate(caseMainInfo.getCaseCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                    List<CaseActsCodeDocVo> docJyDocuments = caseMainInfoMapper.getNoNeedSentDocuments(caseMainInfo.getId());
                    for (CaseActsCodeDocVo doc : docJyDocuments) {
                        //判断文书优先级 签字》印章》原始文件
                        if(StringUtils.isNotBlank(doc.getDocumentUrlAfterSign())){
                            doc.setDocumentUrl(doc.getDocumentUrlAfterSign());
                        }else if(StringUtils.isNotBlank(doc.getDocumentUrlAfterSeal())){
                            doc.setDocumentUrl(doc.getDocumentUrlAfterSeal());
                        }
                    }
                    vo.setDocList(docJyDocuments);
                }
                //处罚种类
                vo.setPunishList(punishList);
                //救济提示
                SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), null);
                vo.setReliefTip(
                        "如不服本处罚决定，可以在收到本决定书之日起 60 日内向" +
                                sysDepartParam.getAdministrativeGovName() +
                                "申请行政复议；也可以在收到本决定书之日起 6 个月内直接向" +
                                sysDepartParam.getAdministrativeActionCourtName() +
                                "起诉，但本决定不停止执行，法律另有规定的除外。逾期不申请行政" +
                                "复议、不提起行政诉讼又不履行的，本机关将依法申请人民法院强制执行或" +
                                "者依照有关规定强制执行。"
                );
                vo.setInvestConclusion(simpleInfo.getInvestConclusion());
                //获取案件进度
                this.getCaseProgress(vo, caseMainInfo, "");
                punishInfoList.add(vo);
            }
        }
        return punishInfoList;
    }

    /**
     * //获取处罚决定信息
     *
     * @param caseMainInfo
     * @param partyTypeMap
     * @param partyNameList
     */
    private List<CasePunishDecisionVo> getActsCodePunishInfoList(CasePublicityActsCodeVo reVo, CaseMainInfo caseMainInfo, Map<String, String> partyTypeMap, List<String> partyNameList,List<CaseReasonActsCodeVo> caseReasonList) {
        //获取处罚决定信息
        List<CasePunishDecisionVo> punishInfoList = new ArrayList<>();
        //先判断是否为分别处罚，如果是分别处罚，则去补充表查询决定书文号，否则去宽表查询决定书文号，决定书日期，根据决定书文号和caseId去文书记录表查询审核通过时间
        //分别处罚
        if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
            auxiliaryExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId());
            List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
            if (auxiliaryInfoList != null && auxiliaryInfoList.size() > 0) {
                boolean showNoPub = false;//判断是否存在处罚决定已送达，但是未公示的记录
                for(CaseMainDetailAuxiliaryInfo e : auxiliaryInfoList){
                    //处罚决定是否已送达
                    boolean isSendDecision = isSendDecision(caseMainInfo.getId(), e.getPartyId());
                    if(!isSendDecision){//处罚决定未送达
                        continue;
                    }
                    //公示判断：选择公示，并且已上报，才是公示
                    if(Constant.STRING_1.equals(e.getIsPublicity())){
                        CasePunishDecisionVo vo = this.getActsCodeCasePunishDecisionVo(e.getPartyName(), e.getPartyId(),partyTypeMap.get(e.getPartyId()), e.getPunishDocumentNumber(), caseMainInfo.getId());
                        //获取公示内容
                        vo.setDecisionContent(e.getPublicityContent());
                        //公示信息
                        if(e.getIsPublicity().equals("1")){
                            //CaseDataReportRecord caseReportRecordInfo = getCaseReportRecordInfo(caseMainInfo.getId(), Arrays.asList(e.getPartyId()));
                            CaseDataReportStageInfo stageInfo = getCaseReportStageInfo(caseMainInfo.getId(), Arrays.asList(e.getPartyId()));
                            LocalDateTime publicDate = this.getPublicDate(caseMainInfo.getId(), e.getPartyId());
                            //公示状态 0:未公示 1:已公示
                            int publicityStatus = stageInfo == null ? Constant.INTEGER_0 : LocalDateTime.now().isAfter(publicDate) ? Constant.INTEGER_1 : Constant.INTEGER_0;
                            //如果是不予处罚的话
                            if(Constant.STRING_2.equals(e.getInvestConclusion())){
                                publicityStatus = Constant.INTEGER_0;
                            }
                            //如果是未上报公示，则跳过
                            if(publicityStatus == Constant.INTEGER_0){
                                showNoPub = true;
                                continue;
                            }
                            //如果是未上报公示，则跳过
                            vo.setPublicityInfo(CaseActsPublicityInfoVo.builder()
                                    .publicityContent(e.getPublicityContent())
                                    .publicityDate(stageInfo == null ? null : publicDate)
                                    .publicityStatus(publicityStatus)
                                    //默认3年
                                    .publicityTerm("3年")
                                    .build());
                        }
                        punishInfoList.add(vo);
                    }else {//处罚决定已送达，但是选择不公示
                        showNoPub = true;
                    }
                }
                //如果punishInfoList有值的话，代表，已送达，并且已上报公示
                if(ObjectUtil.isEmpty(punishInfoList)){
                    reVo.setIsPub(Constant.STRING_0);
                    if(showNoPub){
                        reVo.setNoDecisionReason("依据行政处罚结果信息网上公开相关规定，本案件处罚结果不予公开");
                    }else {
                        reVo.setNoDecisionReason("本案件正在办理中");
                    }
                }else {
                    reVo.setIsPub(Constant.STRING_1);
                }
                //排序
                List<CasePunishDecisionVo> rePunishInfoList = punishInfoList.stream().sorted(Comparator.comparing(CasePunishDecisionVo::getPartyType).reversed()).collect(Collectors.toList());
                return rePunishInfoList;
            }
        } else {//非分别处罚
            if(!Constant.STRING_1.equals(caseMainInfo.getCaseType())) {
                CaseMainDetailInfo queryDetailParam = new CaseMainDetailInfo();
                queryDetailParam.setCaseId(caseMainInfo.getId());
                CaseMainDetailInfo detailInfo = caseMainDetailInfoMapper.selectOne(queryDetailParam);
                //处罚决定是否已送达
                boolean isSendDecision = isSendDecision(caseMainInfo.getId(), "");
                if(!isSendDecision){//处罚决定未送达
                    reVo.setIsPub(Constant.STRING_0);
                    reVo.setNoDecisionReason("本案件正在办理中");
                    return punishInfoList;
                }
                //如果已做出决定（处罚和不予处罚：默认不公示）
                if(Constant.STRING_1.equals(detailInfo.getIsPublicity())){
                    CasePunishDecisionVo vo = this.getActsCodeCasePunishDecisionVo(CollUtil.join(partyNameList, "、"),"", "", detailInfo.getPunishDocumentNumber(), caseMainInfo.getId());
                    vo.setDiscretionInterval(detailInfo.getDiscretionInterval());
                    vo.setDecisionContent(detailInfo.getPublicityContent());
                    //公示信息
                    if(detailInfo.getIsPublicity().equals("1")){
                        //CaseDataReportRecord caseReportRecordInfo = getCaseReportRecordInfo(caseMainInfo.getId(), null);
                        CaseDataReportStageInfo stageInfo = getCaseReportStageInfo(caseMainInfo.getId(), null);
                        LocalDateTime publicDate = this.getPublicDate(caseMainInfo.getId(), "");
                        //公示状态 0:未公示 1:已公示
                        int publicityStatus = stageInfo == null ? Constant.INTEGER_0 : LocalDateTime.now().isAfter(publicDate) ? Constant.INTEGER_1 : Constant.INTEGER_0;
                        //如果是不予处罚的话
                        if(Constant.STRING_2.equals(detailInfo.getInvestConclusion())){
                            publicityStatus = Constant.INTEGER_0;
                        }
                        //如果是未上报公示
                        if(publicityStatus == Constant.INTEGER_0){
                            reVo.setIsPub(Constant.STRING_0);
                            reVo.setNoDecisionReason("依据行政处罚结果信息网上公开相关规定，本案件处罚结果不予公开");
                            return punishInfoList;
                        }
                        reVo.setIsPub(Constant.STRING_1);
                        vo.setPublicityInfo(CaseActsPublicityInfoVo.builder()
                                .publicityContent(detailInfo.getPublicityContent())
                                .publicityDate(stageInfo == null ? null : publicDate)
                                .publicityStatus(publicityStatus)
                                //默认3年
                                .publicityTerm("3年")
                                .build());
                    }
                    punishInfoList.add(vo);
                }else {//未选择公示
                    reVo.setIsPub(Constant.STRING_0);
                    reVo.setNoDecisionReason("依据行政处罚结果信息网上公开相关规定，本案件处罚结果不予公开");
                }
            }else{
                //简易案件一直不公示
                reVo.setIsPub(Constant.STRING_0);
                //处罚决定是否已做出
                boolean isMakeDecision = isMakeDecision(caseMainInfo.getId());
                if(!isMakeDecision){//处罚决定未做出
                    reVo.setNoDecisionReason("本案件正在办理中");
                    return punishInfoList;
                }
                reVo.setNoDecisionReason("依据行政处罚结果信息网上公开相关规定，本案件处罚结果不予公开");
                CasePunishDecisionVo vo = new CasePunishDecisionVo();
                vo.setPartyName(CollUtil.join(partyNameList, "、"));
                vo.setPartyType("");
                vo.setPunishDecisionDate(caseMainInfo.getCaseCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
                vo.setDocumentNumber(caseMainInfo.getCaseNumber());
                punishInfoList.add(vo);
            }
        }
        return punishInfoList;
    }

    /**
     * 设置处罚缴款信息
     */
    private void setPayMentInfo(CaseMainInfo caseMainInfo,CasePunishDecisionVo vo,List<String> partyIdList){
        //获取缴款信息 过滤失效缴款
        List<CaseActsCodePayInfoVo> payVoList = casePaymentMainRecordMapper.getPayInfo(caseMainInfo.getId(),partyIdList);
        if(!CollectionUtils.isEmpty(payVoList)){
            PaymentPromptVo paymentPrompt = new PaymentPromptVo();
            CaseActsCodePayInfoVo payVo = payVoList.get(0);
            paymentPrompt.setNoticeNo(payVo.getNoticeNo());
            paymentPrompt.setPayStatus(StringUtils.isBlank(payVo.getPayStatus()) ? Constant.STRING_2 : payVo.getPayStatus());
            paymentPrompt.setPayMoney(payVo.getPayMoney());
            paymentPrompt.setInvoiceUrl(payVo.getInvoiceUrl());
            paymentPrompt.setPayUrl(payUrl + "?jkdh=" + payVo.getNoticeNo() + "&id=61");
            paymentPrompt.setOverduePayment(payVo.getOverduePayment());
            List<CaseAcsPublicInfoListVo> cfjds = caseMainInfoMapper.getCasePunishDocumentsByDocCode(caseMainInfo.getId(), Arrays.asList("CFJDS"), partyIdList);
            if (!CollectionUtils.isEmpty(cfjds) && cfjds.get(0).getSentTime()!=null) {
                LocalDate expiredPayDate = cfjds.get(0).getSentTime().toLocalDate().plusDays(15);
                paymentPrompt.setExpiredPayDate(expiredPayDate.format(DateTimeFormatter.ofPattern("yyyy.MM.dd")));
                long daysRemaining=expiredPayDate.toEpochDay()-LocalDate.now().toEpochDay();
                paymentPrompt.setDaysRemaining(daysRemaining <= 3 ? daysRemaining + "天后到期":null);
            }
            paymentPrompt.setPayTips("逾期不缴纳罚款的，本机关将根据《中华人民共和国行政处罚法》第七十二条第一款第（一）项的规定，每日按罚款数额的百分之三加处罚款，加处罚款的数额不超出罚款的数额。");

            //线下收款方式
            SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCode(caseMainInfo.getCaseOrgCode(), null);
            if (!ObjectUtils.isEmpty(sysDepartParam)) {
                paymentPrompt.setBankName(sysDepartParam.getPayBankName());
                paymentPrompt.setBankAccountName(sysDepartParam.getPayBankAccountName());
                paymentPrompt.setBankAccount(sysDepartParam.getPayBankAccount());
            }
            vo.setPaymentPrompt(paymentPrompt);
        }
    }
    /**
     * 获取处罚决定信息(行政行为码)
     *
     * @param partyName
     * @param partyType
     * @param punishDocumentNumber
     * @param caseId
     * @return
     */
    private CasePunishDecisionVo getActsCodeCasePunishDecisionVo(String partyName,String partyId, String partyType, String punishDocumentNumber, String caseId) {
        CasePunishDecisionVo vo = new CasePunishDecisionVo();
        vo.setPartyName(partyName);
        vo.setPartyType(partyType);
        vo.setPartyId(partyId);
        vo.setDocumentNumber(punishDocumentNumber);
        vo.setPunishDecisionDate(this.getPunishDecisionDate(caseId, punishDocumentNumber));
        return vo;
    }
    /**
     * 获取当事人信息(行政行为码)
     *
     * @param caseMainInfo
     * @param partyNameList
     * @param partyTypeMap
     */
    private List<CaseActsCodePartyInfoVo> getActsCodePartyInfo(CaseMainInfo caseMainInfo, List<String> partyNameList, Map<String, String> partyTypeMap) {
        Example partyExample = new Example(CasePartiesRecord.class);
        partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId()).andEqualTo("status", "1");
        partyExample.orderBy("partyType").desc();
        List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
        List<CaseActsCodePartyInfoVo> partyInfoList = new ArrayList<>();

        partiesRecords.forEach(e -> {
            CaseActsCodePartyInfoVo vo = new CaseActsCodePartyInfoVo();
            vo.setPartyId(e.getPartyId());
            vo.setPartyType(e.getPartyType());
            vo.setPartyName(e.getPartyName());
            partyInfoList.add(vo);
            partyNameList.add(e.getPartyName());
            partyTypeMap.put(e.getPartyId(), e.getPartyType());
        });
        return partyInfoList;
    }
    @Override
    public List<String> getCasePartyIdsByActsCode(ActsCodeRequest dto) {
        List<String> partyIdList = new ArrayList<>();
        //获取主表数据
        CaseMainInfo queryParam = new CaseMainInfo();
        queryParam.setCaseActsCode(dto.getActsCode());
        CaseMainInfo caseMainInfo = caseMainInfoMapper.selectOne(queryParam);
        if (caseMainInfo == null) {
            throw new BusinessException("未查询到案件信息");
        }
        //用身份证号码查，先查当事人身份为个人身份事的id,再查当事人身份为法人时候的法定代表人身份证号码
        if(StringUtils.isNotBlank(dto.getIdnum())){
            Example partyExample = new Example(CasePartiesRecord.class);
            partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId())
                    .andEqualTo("status", "1");
            partyExample.orderBy("partyType").desc();
            List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
            for (CasePartiesRecord casePartiesRecord : partiesRecords){
                if (!PartyTypeEnum.PERSON.getCode().equals(casePartiesRecord.getPartyType())){
                    CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(casePartiesRecord.getPartyId());
                    if(dto.getIdnum().equals(casePartiesLegalInfo.getLegalCertNo())){
                        partyIdList.add(casePartiesLegalInfo.getId());
                    }
                }else {
                    if(dto.getIdnum().equals(casePartiesRecord.getPartyIdentityCode())){
                        partyIdList.add(casePartiesRecord.getPartyId());
                    }
                }
            }
            /*//先查法定代表人身份
            Example partyLegalExample = new Example(CasePartiesLegalInfo.class);
            partyLegalExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId())
                    .andEqualTo("caseId", caseMainInfo.getId())
                    .andEqualTo("legalCertNo", dto.getIdnum());
            List<CasePartiesLegalInfo> legalInfos = casePartiesLegalInfoMapper.selectByExample(partyLegalExample);
            partyIdList = legalInfos.stream().map(p -> p.getId()).collect(Collectors.toList());
            //先查非法人身份信息
            Example partyExample = new Example(CasePartiesRecord.class);
            partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId())
                    .andEqualTo("partyType", Constant.STRING_1)
                    .andEqualTo("partyIdentityCode", dto.getIdnum())
                    .andEqualTo("status", "1");
            List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
            List<String> persoPartyIdList = partiesRecords.stream().map(p -> p.getPartyId()).collect(Collectors.toList());
            partyIdList.addAll(persoPartyIdList);*/
        }else{
            Example partyExample = new Example(CasePartiesRecord.class);
            partyExample.createCriteria().andEqualTo("caseId", caseMainInfo.getId())
                    .andIn("partyType", Arrays.asList(new String[]{Constant.STRING_2,Constant.STRING_3,Constant.STRING_4}))
                    .andEqualTo("partyIdentityCode", dto.getUniCode())
                    .andEqualTo("status", "1");
            partyExample.orderBy("partyType").desc();
            List<CasePartiesRecord> partiesRecords = casePartiesRecordMapper.selectByExample(partyExample);
            partyIdList = partiesRecords.stream().map(p -> p.getPartyId()).collect(Collectors.toList());
        }
        return partyIdList;
    }

    /**
     * 判断当事人决定书是否存在
     * @return
     */
    private boolean isMakeDecision(String caseId){
        return caseMainInfoMapper.selectJycfJdsDocNum(caseId) > 0 ? true : false;
    }

    /**
     * 判断当事人决定书是否送达
     * @return
     */
    private boolean isSendDecision(String caseId, String partyId){
        return caseMainInfoMapper.selectSendJdsDocNum(caseId, partyId) > 0 ? true : false;
    }

    /**
     * 获取送达决定书的送达时间
     * @param caseId
     * @param partyId
     * @return
     */
    private LocalDateTime getPublicDate(String caseId, String partyId){
        return caseMainInfoMapper.selectJdsDocSendTime(caseId, partyId);
    }


    /**
     * 根据案件ID和证件号码，获取补充表信息
     * @param caseId
     * @param idNum
     * @return
     */
    private List<CaseMainDetailAuxiliaryInfo> getAuxiliaryInfoList(CaseDetailActsCodeVo reVo, String caseId, String idNum){
        List<CaseActsCodePartyInfoVo> partyInfoVoList = reVo.getPartyInfoList();
        List<String> partyIds = CollUtil.newArrayList();
        for (CaseActsCodePartyInfoVo caseActsCodePartyInfoVo : partyInfoVoList){
            if(PartyTypeEnum.LEGAL.getCode().equals(caseActsCodePartyInfoVo.getPartyType())){
                CasePartiesLegalInfo casePartiesLegalInfo = casePartiesLegalInfoMapper.selectByPrimaryKey(caseActsCodePartyInfoVo.getPartyId());
                if(idNum.equals(casePartiesLegalInfo.getLegalCertNo())){
                    partyIds.add(casePartiesLegalInfo.getId());
                }
            }else if(PartyTypeEnum.PERSON.getCode().equals(caseActsCodePartyInfoVo.getPartyType())){
                CasePartiesPersonInfo casePartiesPersonInfo = casePartiesPersonInfoMapper.selectByPrimaryKey(caseActsCodePartyInfoVo.getPartyId());
                if(idNum.equals(casePartiesPersonInfo.getCertNo())){
                    partyIds.add(casePartiesPersonInfo.getId());
                }
            }
        }
        Example auxiliaryExample = new Example(CaseMainDetailAuxiliaryInfo.class);
        auxiliaryExample.createCriteria().andEqualTo("caseId", caseId).andIn("partyId", partyIds);
        List<CaseMainDetailAuxiliaryInfo> auxiliaryInfoList = caseMainDetailAuxiliaryInfoMapper.selectByExample(auxiliaryExample);
        return auxiliaryInfoList;
    }
}
